"""
聊天室管理接口
"""

from fastapi import APIRouter, Depends, HTTPException, status, Form, WebSocket, WebSocketDisconnect
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session
from databases import sessionlocal
from schames import RoomCreate, RoomResponse
from models import ChatRooms, RoomMembers, Messages, User
from auth import get_current_user

chat = APIRouter()


def get_db():
    db = sessionlocal()
    try:
        yield db
    finally:
        db.close()
@chat.post("/rooms/", response_model=RoomResponse, description="创建房间")
async def room_create(room: RoomCreate = Form(), current_user: dict = Depends(get_current_user), db: Session = Depends(get_db)):

    if not room.name:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="聊天室名称不能为空")
    name_flag = db.query(ChatRooms.name).filter(ChatRooms.name == room.name).first()
    if name_flag:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="聊天室名称已存在")
    if room.is_public:
        Room = ChatRooms(create_id=current_user["id"], description=room.description, is_public=room.is_public, name=room.name, password=None)
    else:
        if not room.password:
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="密码不能为空")
        Room = ChatRooms(create_id=current_user["id"], description=room.description, is_public=room.is_public, name=room.name, password=room.password)

    try:
        db.add(Room)
        db.commit()
        member = RoomMembers(room_id=Room.id, user_id=current_user["id"])
        db.add(member)
        db.commit()
        return JSONResponse(content={"message": "创建成功", "room": {"id": Room.id, "name": Room.name, "description": Room.description, "is_public": Room.is_public}})
    except Exception as e:
        print(e)
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="创建失败")


@chat.get("/rooms/", description="列出所有公开聊天室")  # 列出所有公开聊天室,,分页查询;返回所有公开聊天室的name
async def room_list(page: int = 1, page_size: int = 10, current_user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
    try:
        rooms = db.query(ChatRooms).filter(ChatRooms.is_public == True).offset((page - 1) * page_size).limit(page_size).all()
        rooms = [{"id": room.id, "name": room.name, "description": room.description, "is_public": room.is_public} for room in rooms]
        return JSONResponse(content={"message": "查询成功", "rooms": rooms})
    except Exception as e:
        print(e)
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="查询失败")

@chat.get("/{room_id}", description="列出聊天室详细信息") # 列出聊天室详细信息
async def room_detail(room_id: str, current_user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
    if not room_id:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="聊天室id不能为空")
    try:
        room = db.query(ChatRooms).filter(ChatRooms.id == room_id).first()
        if not room:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="聊天室不存在")
        room = {"id": room.id, "name": room.name, "description": room.description, "is_public": room.is_public}
        return JSONResponse(content={"message": "查询成功", "room": room})
    except Exception as e:
        print(e)
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="查询失败")


@chat.post("/{room_id}/join", description="加入聊天室")
async def room_join(room_id: str, current_user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
    if not room_id:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="聊天室id不能为空")
    room = db.query(ChatRooms).filter(ChatRooms.id == room_id).first()
    if not room:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="聊天室不存在")
    if room.is_public:
        member = RoomMembers(room_id=room_id, user_id=current_user["id"])
    else:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="聊天室为私密聊天室，请输入密码")
    try:
        db.add(member)
        db.commit()
        return JSONResponse(content={"message": "加入成功"})
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="加入失败")

@chat.post("/{room_id}/join_secret", description="加入私密聊天室")
async def room_join_secret(room_id: str, password: str = Form(), current_user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
    if not room_id:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="聊天室id不能为空")
    room = db.query(ChatRooms).filter(ChatRooms.id == room_id).first()
    if not room:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="聊天室不存在")
    if room.password != password:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="密码错误")
    member = RoomMembers(room_id=room_id, user_id=current_user["id"])
    try:
        db.add(member)
        db.commit()
        return JSONResponse(content={"message": "加入成功"})
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="加入失败")

@chat.delete("/{room_id}/leave", description="退出聊天室")
async def room_leave(room_id: str, current_user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
    if not room_id:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="聊天室id不能为空")
    room = db.query(ChatRooms).filter(ChatRooms.id == room_id).first()
    if not room:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="聊天室不存在")
    member = db.query(RoomMembers).filter(RoomMembers.room_id == room_id, RoomMembers.user_id == current_user["id"]).first()
    if not member:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="您不在该聊天室中")
    if room.create_id == current_user["id"]:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="您是该聊天室创建者，无法退出")
    try:
        db.delete(member)
        db.commit()
        return JSONResponse(content={"message": "退出成功"})
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="退出失败")

@chat.delete("/rooms/{room_id}/", description="删除聊天室")
async def room_delete(room_id: str, current_user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
    if not room_id:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="聊天室id不能为空")
    room = db.query(ChatRooms).filter(ChatRooms.id == room_id).first()
    if not room:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="聊天室不存在")
    if room.create_id != current_user["id"] and current_user["role"] != "admin":
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="您不是该聊天室创建者")
    try:
        db.delete(room)
        db.commit()
        return JSONResponse(content={"message": "删除成功"})
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="删除失败")

@chat.websocket("/ws/{room_id}")
async def websocket_endpoint(websocket: WebSocket, room_id: int, user_id: int, db: Session = Depends(get_db)):
    current_user = db.query(User).filter(User.id == user_id).first()
    Room = db.query(RoomMembers).filter(RoomMembers.room_id == room_id, RoomMembers.user_id == user_id).first()
    current_user = {"id": current_user.id, "nickname": current_user.nickname, "role": Room.role}
    role = "群主" if current_user["role"] == "admin" else "成员"
    await websocket.accept()
    await websocket.send_text(f"{role}{current_user['nickname']}加入群聊")
    try:
        while True:
            data = await websocket.receive_text()
            if not data:
                raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="聊天内容不能为空")
            message = Messages(content=data, room_id=room_id, user_id=current_user["id"])
            db.add(message)
            db.commit()
            for member in db.query(RoomMembers).filter(RoomMembers.room_id == room_id).all():
                await websocket.send_text(f"{role}{current_user['nickname']}说: {data}")
    except WebSocketDisconnect:
        print(f"{role}{current_user['nickname']} disconnect")
    except Exception as e:
        print(e)
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="失败")


@chat.get("/{room_id}/messages", description="获取聊天室消息")
async def room_messages(room_id: str, current_user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
    if not room_id:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="聊天室id不能为空")
    room = db.query(ChatRooms).filter(ChatRooms.id == room_id).first()
    if not room:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="聊天室不存在")
    messages = db.query(Messages).filter(Messages.room_id == room_id).all()
    return {"data": [{"content": message.content, "content_type": message.content_type, "create_at": message.create_at, "time_stamp": message.time_stamp, "user_id": message.user_id} for message in messages]}